package com.dragon.modules.yuegou.client.wechat_mini.client.impl;

import com.dragon.modules.yuegou.client.wechat_mini.client.WxaCodeClient;
import com.dragon.modules.yuegou.client.wechat_mini.common.BaseResponse;
import com.dragon.modules.yuegou.client.wechat_mini.conn.IMiniClient;
import com.dragon.modules.yuegou.client.wechat_mini.request.QrcodeRequest;
import com.dragon.modules.yuegou.client.wechat_mini.request.UnlimitedQrcodeRequest;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

public class WxaCodeClientImpl implements WxaCodeClient {

	private final IMiniClient client;
	
	private final ObjectMapper mapper = new ObjectMapper();

	public WxaCodeClientImpl(IMiniClient client) {
		this.client = client;
	}

	@Override
	public byte[] createQRCode(String accessToken, String path, Integer width) {
		Map<String, Object> params = new LinkedHashMap<>();
		params.put("path", path);
		if(width != null) {
			params.put("width", width);
		}
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		client.post("/cgi-bin/wxaapp/createwxaqrcode")
				.accessToken(accessToken)
				.json(params)
				.execute(output);
		return output.toByteArray();
	}

	@Override
	public byte[] get(String accessToken, QrcodeRequest request) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		client.post("/wxa/getwxacode")
				.accessToken(accessToken)
				.json(request)
				.execute(output);
		return output.toByteArray();
	}

	@Override
	public byte[] getUnlimited(String accessToken, UnlimitedQrcodeRequest request) {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		client.post("/wxa/getwxacodeunlimit")
				.accessToken(accessToken)
				.json(request)
				.execute(output);
		byte[] data = output.toByteArray();
		
		if(data.length < 200) {
			try {
				BaseResponse resp = mapper.readerFor(BaseResponse.class).readValue(data);
				resp.check();
			} catch (IOException e) {
				// ignore
			}
		}
		
		return data;
	}

}
